import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QPushButton, QLineEdit

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('PyQt Calculator')
        # 创建只读的显示屏
        self.display = QLineEdit(self)
        self.display.setReadOnly(True)
        grid = QGridLayout()
        self.setLayout(grid)
        # 定义按钮和位置
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]
        positions = [(i, j) for i in range(4) for j in range(4)]
        for position, name in zip(positions, buttons):
            if name == '=':
                btn = QPushButton(name)
                # 绑定计算事件
                btn.clicked.connect(self.calculate)
            else:
                btn = QPushButton(name)
                # 绑定输入事件
                btn.clicked.connect(lambda checked, b=name: self.display.setText(self.display.text() + b))
            grid.addWidget(btn, *position)
        # 添加显示屏，跨4列
        grid.addWidget(self.display, 0, 0, 1, 4)
        # 清零按钮
        self.clear_btn = QPushButton('C')
        self.clear_btn.clicked.connect(self.display.clear)
        grid.addWidget(self.clear_btn, 4, 0, 1, 4)

    def calculate(self):
        try:
            # 计算并显示结果
            result = eval(self.display.text())
            self.display.setText(str(result))
        except:
            self.display.setText("Error")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calc = Calculator()
    calc.show()
    sys.exit(app.exec_())